package org.grill.fatwhacker.gui;

import java.util.ArrayList;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.grill.fatwhacker.data.FoodWeek;
import org.grill.fatwhacker.data.WeekSet;

public class WeekSelectionView {

	private Table weekTable;
	private WeekSet weekSet;

	public void setWeekSet(WeekSet weekSet) {
		this.weekSet = weekSet;
	}

	public WeekSelectionView(Composite weekComposite) {
		weekTable = new Table(weekComposite, SWT.NONE);
		TableColumn tableColumn = new TableColumn( weekTable, SWT.NONE);
		tableColumn.setText("Week");
		tableColumn.setWidth(200);
		weekTable.setHeaderVisible(true);
		weekTable.pack();
		
		weekTable.addSelectionListener(new SelectionListener() {
		
			public void widgetSelected(SelectionEvent arg0) {
				TableItem[] selection = weekTable.getSelection();
				if (selection == null || selection.length == 0) return;
				
				TableItem item = selection[0];
				currentWeek = (FoodWeek) item.getData();
				
				for (Listener l : listeners)
					l.handleEvent(new Event());
			}
		
			public void widgetDefaultSelected(SelectionEvent arg0) {
		
			}
		
		});
	}

	private FoodWeek currentWeek;
	
	public void setCurrentWeek(FoodWeek currentWeek) {
		this.currentWeek = currentWeek;
	}
	
	public FoodWeek getCurrentWeek() {
		return currentWeek;
	}
	
	private ArrayList<Listener> listeners = new ArrayList<Listener>();
	
	public void addListener(Listener l) {
		listeners.add(l);
	}
	
	
	public void render() {
		weekTable.clearAll();
		
		for (FoodWeek week : weekSet) 
		{
			TableItem item = new TableItem(weekTable, SWT.NONE);
			item.setText(week.toString());
			item.setData(week);
			if (week == currentWeek) 
				weekTable.setSelection(item);
		}
	}
}
